package bio;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class BioServer {

    private static ExecutorService executorService = Executors.newFixedThreadPool(4);

    public static void main(String[] args) {
        try (ServerSocket serverSocket = new ServerSocket()) {
            serverSocket.bind(new InetSocketAddress(8080));

            while (true) {
                Socket socket = serverSocket.accept();
                executorService.submit(new SocketHandler(socket));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            executorService.shutdown();
        }
    }
}

class SocketHandler implements Runnable {

    private final Socket socket;

    SocketHandler(Socket socket) {
        this.socket = socket;
    }

    public void run() {
        byte[] message = new byte[8];
        try (BufferedInputStream inputStream = new BufferedInputStream(socket.getInputStream());) {
            while (inputStream.read(message) != -1) {
                System.out.println(new String(message));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}